// pages/famousDetail/famousDetail.js
var app=getApp();
var util=require("../../utils/util");
var home=require("../../api/home");
var config=require("../../api/config");

Page({
  /*页面的初始数据*/
  data: {
    width: wx.getSystemInfoSync().windowWidth,
    info: '',
    uid: '',
    oid: '',
    cur_nav: 0,
    bar_text:["介绍","课程","评价"],
    fix: false,
    show_scroll: true,
    scroll_arr: [0,0,0],
    cour_list: [],
    com_list:[],
    latitude: 22.820794,
    longitude: 113.284565,
    currentPage1: 1,
    currentPage2: 1,
    pageSize: 10,
    hasMoreDate1: true,
    hasMoreDate2: true,
    token: '',
    educations:['小学','初中','高中','专科','本科','硕士','博士'],
    show_cont: false
  },
  /*生命周期函数--监听页面加载*/
  onLoad: function (options) {
    // console.log(options)
    var that=this,uid='',oid='';
    if(options.scene){
      var sence=decodeURIComponent(options.scene).split("I");
      uid=sence[0];
      oid=sence[1];
    }else{
      uid=options.uid
      oid=options.oid
    }
    that.setData({uid:uid,oid:oid,token:wx.getStorageSync('token')})
    wx.getStorage({
      key: 'city',
      success:function(res){
        var info=res.data;
        that.setData({latitude:info.lat,longitude:info.lng})
        that.get_teach_info(uid,oid)
      },
      fail:function(){
        that.get_teach_info(uid,oid)
      },
    })
    var type=options.type?options.type:0,key=["未知","附近名师","课程详情","机构详情","拼团课详情","我的收藏"]

    // 事件统计
    app.td_app_sdk.event({
      id: 'famousDetail',
      label: '老师详情',
      params: {
        key1: key[type]
      }
    })
  },
  // 关注
  user_follow:function(e){
    var that=this,info=that.data.info,token=that.data.token;
    var id=e.currentTarget.dataset.id;
    if(token){
      if(info.focus){
        that.cancel_focus_teacher(id)
      }else{
        that.add_focus_teacher(id)
      }
    }else{
      wx.navigateTo({
        url: '../login/login',
      })
    }
  },
  // 预览
  preview_img:function(e){
    var that=this,info=that.data.info;
    var type=e.currentTarget.dataset.num;
    if(type==1){
      wx.previewImage({
        current: info.certificates[0],
        urls: info.certificates
      })
    }else{
      wx.previewImage({
        current: info.styles[0],
        urls: info.styles
      })
    }
  },
  // 导航
  check_nav:function(e){
    var that=this,cur_nav=that.data.cur_nav,scroll_arr=that.data.scroll_arr,fix=that.data.fix;
    var index=e.currentTarget.dataset.index;
    if(cur_nav!=index){
      that.setData({cur_nav:index,currentPage: 1})
    }
    if(fix){
      that.setData({show_scroll:false})
      if(scroll_arr[0]>0){
        wx.pageScrollTo({
          scrollTop: scroll_arr[index],
          duration: 10
        })
      }
      setTimeout(function(){that.setData({show_scroll: true})},1000)
    }
    // 事件统计
    app.td_app_sdk.event({
      id: 'famousCut',
      label: '老师详情切换',
      params: {
        key1: that.data.bar_text[index]
      }
    })
  },
  // 滚动定位
  onPageScroll:function(e){
    var that=this,scroll_top=that.data.scroll_top,cur_nav=that.data.cur_nav,scroll_arr=that.data.scroll_arr,show_scroll=that.data.show_scroll;
    var page_scroll=e.scrollTop;
    // console.log(page_scroll)
    if(page_scroll>scroll_top){
      if(!that.data.fix){
        that.setData({fix: !that.data.fix})
      }
      if(show_scroll){
        for(var i=0;i<scroll_arr.length;i++){
          scroll_arr[cur_nav]=page_scroll;
          if(scroll_arr[i] == 0){
            scroll_arr[i]=20;
          }
        }
      }
    }else{
      if(that.data.fix){
        that.setData({fix: !that.data.fix})
      }
    }
  },
  nav_home:function(){
    // wx.navigateBack({
    //   delta: 1
    // });
    wx.reLaunch({
      url: '../famousMaster/famousMaster',
    })
  },
  // 分享
  onShareAppMessage:function(){
    var that=this,info=that.data.info;
    return{
      title: info.realName+'老师',
      path: '/pages/famousDetail/famousDetail?uid='+info.userId+'&oid='+info.orgId,
      imageUrl: info.avatar
    }
  },
  onShareTimeline:function(){
    var that=this,info=that.data.info;
    return{
      title: info.realName+'老师',
      query: 'uid='+info.userId+'&oid='+info.orgId,
      imageUrl: info.avatar
    }
  },
  // 触底
  onReachBottom:function(){
    var that=this,show_scroll=that.data.show_scroll,cur_nav=that.data.cur_nav,uid=that.data.uid,oid=that.data.oid;
    var hasMoreData=cur_nav==1?that.data.hasMoreData1:cur_nav==2?that.data.hasMoreData2:'';
    if(show_scroll){
      if(hasMoreData){
        if(cur_nav==1){
          that.get_teach_cour(uid,oid)
        }else if(cur_nav==2){
          that.get_teach_comment(uid,oid)
        }
      }else{
        if(cur_nav!=0){
          util.page_show_toast('没有更多了',1500)
        }
      }
    }
  },
  //
  onShow:function(){
    var that=this;
    if(app.globalData.login){
      app.globalData.login=false;
      app.globalData.change_dom=false;
      app.globalData.change_table=false;
      var token=wx.getStorageSync('token');
      //
      that.setData({token:token,cour_list:[],com_list:[],currentPage1:1,currentPage2:1,hasMoreDate1:true,hasMoreDate2:true})
      //
      that.get_teach_info(that.data.uid,that.data.oid)
    }
  },
  // 
  onReady:function(){
    var that = this;
    var query = wx.createSelectorQuery();
    query.selectAll('.page_top').boundingClientRect(function (res) {
      // console.log(res)
      that.setData({scroll_top: res[0].height})
    }).exec()
  },
  // 获取详情
  get_teach_info:function(uid,oid){
    wx.showLoading({title: '加载中'})
    var that=this,educations=that.data.educations;
    var params={
      "userId": uid,
      "orgId": oid,
      "lat": that.data.latitude,
      "lng": that.data.longitude
    }
    home.get_teach_info(params).then(res=>{
      if(res.data.code==200){
        var info=res.data.data;
        if(!info){
          util.page_show_toast("老师资料尚未完善",1500)
          setTimeout(()=>{
            wx.navigateBack({
              delta: 0,
            })
          },1500)
          return false;
        }
        info.realName=info.realName?(info.realName.indexOf("老师")>-1?info.realName:info.realName+"老师"):'';
        info.space=info.distance>1000?(info.distance/1000).toFixed(2):info.distance;
        info.yearCount=info.teachingTime?new Date().getFullYear()-new Date(info.teachingTime).getFullYear()+1:'';
        info.count=info.studentCount>=10000?Math.ceil(info.studentCount/10000)+'w':info.studentCount;
        info.grades=info.grades?info.grades.split(','):info.grades;
        info.certificates=info.certificates?info.certificates.split(","):info.certificates;
        info.styles=info.styles?info.styles.split(","):info.styles;
        info.educaName=info.education?educations[Number(info.education)-1]:'';
        info.positiveRate=info.positiveRate?info.positiveRate*100+'%':''
        if(info.certificates&&info.certificates.length>0){
          info.certificates.pop()
        }
        if(info.styles&&info.styles.length>0){
          info.styles.pop()
        }
        // 
        if(info.grades){
          that.get_grade_list(info)
        }else{
          that.setData({info:info})
        }
        //
        if(info.graduationSchool||info.education||info.jobs||info.grades||info.score||info.trait||info.certificates||info.styles){
          that.setData({show_cont: false})
        }else{
          that.setData({show_cont: true})
        }
        that.get_teach_cour(uid,oid)
        that.get_teach_comment(uid,oid)
      }else if(res.data.code==500){
        util.page_show_toast("网络请求出错，请稍后再试",2000)
        setTimeout(()=>{
          wx.navigateBack({
            delta: 1,
            fail:function(){
              wx.switchTab({
                url: '/pages/home/home',
              })
            }
          })
        },2000)
      }
    })
  },
  // 在读年级列表
  get_grade_list:function(info){
    var that=this,grade_list=[];
    config.get_grade_list().then(res=>{
      if(res.data.code==200){
        var list=res.data.data;
        for(var i=0;i<list.length;i++){
          for(var j=0;j<list[i].gradeList.length;j++){
            for(var m=0;m<info.grades.length;m++){
              if(info.grades[m]==list[i].gradeList[j].value){
                grade_list.push(list[i].gradeList[j].text)
              }
            }
          }
        }
        info.gradeNames=grade_list.join("，")
        that.setData({info:info})
      }
    })
  },
  // 课程列表
  get_teach_cour:function(uid,oid){
    wx.showLoading({title: '加载中'})
    var that=this,currentPage=that.data.currentPage1,pageSize=that.data.pageSize;
    var params={
      "teacherId": uid,
      "businessId": oid,
      "currentPage": currentPage,
      "pageSize": pageSize
    }
    home.get_teach_cour(params).then(res=>{
      if(res.data.code==200){
        var list=res.data.data.records;
        for(var i=0;i<list.length;i++){
          list[i].introducePictures=list[i].introducePictures?list[i].introducePictures.split(","):'';
          list[i].courseNatureName=list[i].courseNatureName?list[i].courseNatureName.substr(0,2):'';
          list[i].score=list[i].score?list[i].score.toFixed(1):'0.0';
          list[i].labelName=list[i].labelName?list[i].labelName.split(","):''
          list[i].sellCount=list[i].sellCount?list[i].sellCount:0
        }
        var cour_list = that.data.cour_list;
        cour_list = util.extend(cour_list, list)
        if (list.length < pageSize) {
          that.setData({
            cour_list: cour_list,
            hasMoreData1: false
          })
        } else {
          that.setData({
            cour_list: cour_list,
            hasMoreData1: true,
            currentPage1: currentPage + 1
          })
        }
      }
    })
  },
  // 评论列表
  get_teach_comment:function(uid,oid){
    wx.showLoading({title: '加载中'})
    var that=this,currentPage=that.data.currentPage2,pageSize=that.data.pageSize;
    var params={
      "teacherId": uid,
      "businessId": oid,
      "currentPage": currentPage,
      "pageSize": pageSize
    }
    home.get_teach_comment(params).then(res=>{
      if(res.data.code==200){
        var list=res.data.data.records;
        for(var i=0;i<list.length;i++){
          list[i].time=list[i].createTime?util.formatTime_com_time(list[i].createTime):util.formatTime_com_time(new Date().getTime());
          list[i].star=["","","","",""]
        }
        var com_list = that.data.com_list;
        com_list = util.extend(com_list, list)
        if (list.length < pageSize) {
          that.setData({
            com_list: com_list,
            hasMoreData2: false
          })
        } else {
          that.setData({
            com_list: com_list,
            hasMoreData2: true,
            currentPage2: currentPage + 1
          })
        }
      }
    })
  },
  // 收藏
  add_focus_teacher:function(id){
    var that=this,token=that.data.token,info=that.data.info;
    var params={
      "beFocusedId": id
    }
    home.add_focus_teacher(params,token).then(res=>{
      if(res.data.code==200){
        util.page_show_toast('收藏成功',1500)
        info.focus=true;
        that.setData({info:info})
      }
    })
  },
  // 取消收藏
  cancel_focus_teacher:function(id){
    var that=this,token=that.data.token,info=that.data.info;
    var params={
      "beFocusedId": id
    }
    home.cancel_focus_teacher(params,token).then(res=>{
      if(res.data.code==200){
        util.page_show_toast('取消收藏成功',1500)
        info.focus=false;
        that.setData({info:info})
      }
    })
  },
})